package com.hejjon.util;

import com.hejjon.core.exception.BusinessException;
import com.hejjon.enumer.DriverEnum;
import com.hejjon.pojo.ConnectionInfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author: cs
 * @date: 2025-02-21 17:27:12
 * @since: 1.0
 */
public class JDBCUtils {


    /**
     * 获取 JDBC 数据库连接
     *
     * @param connInfo
     * @return
     */
    public static Connection takeJdbcConnection(ConnectionInfo connInfo) {

        Connection conn = null;
        String driver = connInfo.getDriver();
        String url = connInfo.getUrl();
        String username = connInfo.getUsername();
        String password = connInfo.getPassword();

        try {
            // 加载驱动
            Class.forName(driver);
            // 获取连接
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new BusinessException("获取数据库连接出现异常, " + e.getMessage());
        }
        return conn;
    }


    /**
     * 拼接连接URL字符串
     * @param host
     * @param port
     * @param driverType
     * @return
     */
    public static String getUrlByInfo(String host, Long port, String driverType) {
        DriverEnum driverEnum = DriverEnum.getInstance(driverType);
        if (driverEnum == null) {
            throw new BusinessException("未知的驱动类型: " + driverType);
        }
        switch (driverEnum) {
            case MYSQL:
                return "jdbc:mysql://" + host + ":" + port + "/";
            case ORACLE:
                return "jdbc:oracle:thin:@" + host + ":" + port + ":orcl";
            case SQL_SERVER:
                return "jdbc:sqlserver://" + host + ":" + port + ";";
        }
        return "";
    }


}
